package com.idea.relax.exception.error;

import com.idea.relax.exception.api.BaseException;
import com.idea.relax.exception.config.ExceptionKitProperties;
import com.idea.relax.exception.alarm.ErrorAlarmEventPublisher;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;


/**
 * @author: 沉香
 * @date: 2023/2/28
 * @description: 处理BaseException类型的异常
 */
@Slf4j
@Order
@RestControllerAdvice
@AllArgsConstructor
public class BaseExceptionTranslator {

	private final ExceptionKitProperties properties;

	/**
	 * 处理BaseException类型的异常
	 *
	 * @param e BaseException
	 * @return
	 */
	@ExceptionHandler(BaseException.class)
	public Map<String, Object> baseException(BaseException e) {
		ErrorAlarmEventPublisher.alarmIfAllow(e, properties);
		log.error("异常码:{},异常等级:{},异常类型:{},异常类:{}", e.getErrorCode(), e.getLevel(), e.getType(), e.getClass().getSimpleName());
		return buildResponseMap(e);
	}


	private Map<String, Object> buildResponseMap(BaseException e) {
		Map<String, Object> ret = new HashMap<>(16);
		ret.put("code", e.getCode());
		ret.put("errorCode", e.getErrorCode());
		ret.put("message", e.getMessage());
		ret.put("errorLevel", e.getLevel());
		ret.put("errorType", e.getType());
		ret.put("userTip", e.getUserTip());
		return ret;
	}


}
